package myNewProject.downloader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

public class IODownloader implements Downloader {


    //获取整个页面所有源码
    @Override
    public StringBuilder getSourceCode(String link) {
        StringBuilder result = new StringBuilder();
        InputStreamReader inputStreamReader = null;
        try {
            URL url = new URL(link);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36");
            inputStreamReader = new InputStreamReader(urlConnection.getInputStream(),Charset.forName("gbk"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try(BufferedReader in = new BufferedReader(inputStreamReader)) {
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result.append(inputLine);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}


